Ext.define('Seq.pivot.Clipboard', {
    extend: 'Ext.pivot.Grid',

    requires: ['Ext.grid.selection.SpreadsheetModel', 'Ext.grid.plugin.Clipboard',
        'Ext.grid.selection.Replicator', 'Ext.pivot.update.Overwrite', 'Ext.pivot.plugin.CellEditing',
        'Ext.pivot.plugin.Exporter'],

    selModel: {
        type: 'spreadsheet'
    },

    plugins: ['clipboard', 'selectionreplicator', {
        ptype: 'pivotcellediting',
        clicksToEdit: 1,
        defaultUpdater: 'uniform'
    }, 'pivotexporter'],

    getModifiedRecs: function () {
        var pivot = this, store = pivot.getStore();
        pivot.updateParseValue();
        return store.getModifiedRecords();
    },

    commitChanges: function () {
        var pivot = this, store = pivot.getStore();
        store.commitChanges();
        pivot.getView().getStore().commitChanges();
    },

    privates: {
        getArrayStoreModified: function (store) {
            var result = new Array();
            var items = store.getDataSource().items;
            for (var i in items) {
                if (items[i].dirty) {
                    result.push(items[i]);
                }
            }
            return result;
        },

        updateParseValue: function () {
            var me = this, matrix = me.getMatrix();

            var store = me.getView().getStore();
            var arrayRecs = me.getArrayStoreModified(store);

            if (Ext.isEmpty(matrix) || Ext.isEmpty(arrayRecs)) {
                return new Array();
            }

            var columns = me.getColumns(), columnsMap = new Map();
            for (var i in columns) {
                columnsMap.set(columns[i].dataIndex, columns[i]);
            }
            for (var i in arrayRecs) {
                var arrayRec = arrayRecs[i], arrayModified = arrayRec.modified;
                for (var c in arrayModified) {
                    var column = columnsMap.get(c);
                    if (column) {
                        var leftItem = me.getLeftAxisItem(arrayRec);
                        var topItem = me.getTopAxisItem(column)
                        if (leftItem && topItem) {
                            var pviotItem = matrix.results.get(leftItem.key, topItem.key);
                            if (pviotItem && pviotItem.records) {
                                var records = pviotItem.records, j, len = records.length;
                                for (j = 0; j < len; j++) {
                                    records[j].set(column.dimension.dataIndex, arrayRec.data[c]);
                                }
                            }
                        }
                    }
                }
            }
        }
    },
    listeners: {
        pivotbeforeupdate: function () {
            this.updateParseValue();
        }
    }
});